import store from './index'
import request from '@/utils/drawutils/request';
import { formatDate } from "@/utils/drawdat/date"

import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  state: {
    socket: null,
    clientid: "",

  },
  mutations: {
    SET_SOCKET(state, socket) {
      state.socket = socket
    },
    SET_CLIENTID(state, clientid) {
      state.clientid = clientid
    },
  },


  actions: {
    //联接websocket服务器
    createSocket({ state, commit }, bGetData = false) {
      if (state.socket != null) {
        console.log("connected!")
        return
      }

      var now = new Date()
      var clientid = formatDate(now, "yyyyMMdd-hhmmss-SSS")
      console.log("clientid:", clientid)

      var remoteSvrIp = window.location.hostname
      console.log( "remote ip: "  ,remoteSvrIp )
      var socket = new WebSocket('ws://'+ remoteSvrIp +':9191/getData/' + clientid)

      socket.onopen = function () {
        console.log("websocket已打开");
        commit('SET_SOCKET', socket);
        commit('SET_CLIENTID', clientid);
        if( bGetData ){
          store.dispatch('callData')

          setTimeout(() => {
            store.dispatch('sendProjectInfo')
          }, 1000);
        }
          
        // console.log( "clientid:", clientid )
      };

      //  浏览器端收消息，获得从服务端发送过来的文本消息
      socket.onmessage = function (msg) {
        //console.log( "on message",  msg.data)
        const jsonvalue = JSON.parse(msg.data)

        const msgarray = jsonvalue.data
        if (msgarray) {
          for (var i = 0; i < msgarray.length; i++) {
            let obj = msgarray[i]
            commit('setValue', { componentData: state.componentData, indexid: obj.indexid, 
              objid: obj.objid, array: obj.array } )

            // for (var j = 0; j < obj.array.length; j++) {
            //   commit('setValue', { componentData: state.componentData, indexid: obj.indexid, 
            //     objid: obj.objid, fValue: obj.array[j].value })
            // }
          }
        }
        if (jsonvalue.alarm) {
          for (var i = 0; i < jsonvalue.alarm.length; i++) {
            commit('addAlarmStr', jsonvalue.alarm[i])
          }
        }
        if (jsonvalue.info) {
          for (var i = 0; i < jsonvalue.info.length; i++) {
            // console.log( jsonvalue.info[i] )
            commit('addInfoStr', jsonvalue.info[i])
          }
        }

      };
      //关闭事件
      socket.onclose = function () {
        console.log("websocket已关闭");
        commit('SET_SOCKET', null);
      };
      //发生了错误事件
      socket.onerror = function () {
        console.log("websocket发生了错误");
        commit('SET_SOCKET', null);
      };

    },

    //召唤画面所需的数据
    callData({ state, commit }) {
      let requestarray = []
      for (var i = 0; i < state.componentData.length; i++) {
        const obj = state.componentData[i]

        //一个对象中有多个编号
        var datarray = []

        if (Object.keys(obj.hg3000.linkid).length > 0) {
          datarray.push(obj.hg3000.linkid)
        }

        if (Object.keys(obj.hg3000.linkids).length > 0) {
          for (let j = 0; j < obj.hg3000.linkids.length; j++) {
            datarray.push(obj.hg3000.linkids[j]);
          }
        }

        //requestarray数组中每一个元素是一个对象，每个对象可以有多个数据采集点dataarray(dbid, key, descr, field)
        if (datarray.length > 0) {
          //数组中的对象信息包括  对象编号  对象序号  该对象的数据点数组
          let datobj = { objid: obj.id, indexid: i, array: datarray }    //objid 为对象的编号 
          requestarray.push(datobj)
        }
      }  //end for

      

      //发送时的信息： 客户编号  与 对象信息数组
      let sendobj = { clientid: state.clientid, 
        callfunc: "calldata", array: requestarray }

      console.log("call  sendobj",  sendobj )

      //发送
      state.socket.send(JSON.stringify(sendobj))
    },


    sendProjectInfo({ state, commit }) {
      let projectinfo = { prefix: state.prefix, project_id: state.project_id }
      let sendobj = { clientid: state.clientid, 
        callfunc: "projectinfo", projectinfo: projectinfo }

      console.log("projectinfo  sendobj",  sendobj )
      state.socket.send(JSON.stringify(sendobj))      
    }
  },
}
